﻿using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Dome.Models
{
    public class ContentHub : Hub
    {
        // 用户与ID对应
        private static Dictionary<string, string> _connections = new Dictionary<string, string>();
        public async Task SendMessage(string user, string message)
        {
            await Clients.All.SendAsync("ReceiveMessage", user, message);
        }
        public override async Task OnConnectedAsync()
        {
            //获取路由参数,登陆后可将用户id传入，用于关联
            var name = Context.GetHttpContext().Request.Query["userName"];

            //新增加的连接，需要将其保存
            var connid = Context.ConnectionId;
            //全部发送
            await Clients.All.SendAsync("ReceiveMessage", "系统消息", "新人加入");
            //只给他发送
            await Clients.Client(connid).SendAsync("ReceiveMessage", "系统消息", "加入成功");
            //除他之外都发送
            await Clients.AllExcept(connid).SendAsync("ReceiveMessage", "系统消息", "新人加入");
            //添加群组
            await Groups.AddToGroupAsync(connid, "groupname");
            //移除群组
            await Groups.RemoveFromGroupAsync(connid, "groupname");
            //群组发送
            await Clients.Groups("groupname").SendAsync("ReceiveMessage");
            //触发当前的调用者
            await Clients.Caller.SendAsync("ReceiveMessage", "系统消息", "已连接");
            //除当前触发者之外
            await Clients.Others.SendAsync("ReceiveMessage", "系统消息", "已连接");

            //用户名添加(不存在的Add到字典表，存在的进行修改)
            SendLogin(name);


        }
        //客户端连接成功保存用户名和客户都安Id
        public void SendLogin(string username)
        {
            //判断用户有没有登陆过(没登陆过插入用户名和Id，登陆过修改用户名和Id)
            if (!_connections.ContainsKey(username))
            {
                _connections.Add(username, Context.ConnectionId);
            }
            else
            {
                _connections[username] = Context.ConnectionId;
            }
        }
        public override async Task OnDisconnectedAsync(Exception exception)
        {
            //已断开的连接id，需要将其移除
            var connId = Context.ConnectionId;

            var a = Context.ConnectionId;//客户端Id
            List<string> dik = valeToKey(_connections, a);//根据Id查出客户端名称
            if (dik.Count == 1)
            {
                _connections.Remove(dik[0]);//删除掉字典表中这个人
            }
            

            await Clients.Caller.SendAsync("ReceiveMessage", "系统消息", "已退出");

        }
        //根据value找到key
        public List<string> valeToKey(Dictionary<string, string> dkv, string vle)
        {
            List<string> resultKey = new List<string>();
            foreach (var key in dkv.Keys)
            {
                if (dkv[key] == vle)
                {
                    resultKey.Add(key);
                }
            }
            return resultKey;
        }
    }
}
